package me.cjj.android.assignment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Random;

import io.github.kexanie.library.MathView;
import me.cjj.android.assignment.model.IQuestion;
import me.cjj.android.assignment.model.LinearQuestion;
import me.cjj.android.assignment.model.QuadraticQuestion;

@SuppressLint("SetTextI18n")
public class QuizActivity extends AppCompatActivity {

    private Button btnSubmit;
    private Button btnNext;
    private MathView tvQuestion;
    private TextView tvResult;
    private LinearLayout llAnswer;

    public static void start(Context context) {
        Intent starter = new Intent(context, QuizActivity.class);
        context.startActivity(starter);
    }

    private int currentPosition = 0;
    private IQuestion currentQuestion;
    private long[] timeCost = new long[10];
    private boolean[] correctResult = new boolean[10];

    private long startTime;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz);
        btnSubmit = findViewById(R.id.btnSubmit);
        btnNext = findViewById(R.id.btnNext);
        tvResult = findViewById(R.id.tvResult);
        tvQuestion = findViewById(R.id.tvQuestion);
        llAnswer = findViewById(R.id.llAnswer);
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submit();
            }
        });
        onNext(tvQuestion);
        startTime = System.currentTimeMillis();
        currentQuestion = generateLinear();
        String questionText = currentQuestion.getQuestionText();
        tvQuestion.setText(questionText + ", what is x");
        generateAnswerLayout(llAnswer, currentQuestion);
    }

    public boolean submit() {
        int childCount = llAnswer.getChildCount();
        float[] answers = new float[childCount];
        for (int i = 0; i < childCount; i++) {
            EditText editText = ((EditText) llAnswer.getChildAt(i));
            String answer = editText.getText().toString();
            if (answer.isEmpty()) {
                Toast.makeText(this, "Please enter all answer", Toast.LENGTH_LONG).show();
                return false;
            }
            try {
                answers[i] = Float.parseFloat(answer);
            } catch (Exception e) {
                Toast.makeText(this, "Please answer with float", Toast.LENGTH_LONG).show();
                return false;
            }
        }
        boolean judgeResult = currentQuestion.judge(answers);
        if (judgeResult) {
            tvResult.setText("Correct!!!");
        } else {
            String answerText = currentQuestion.getAnswerText();
            tvResult.setText("Wrong Answer,corrent answer is " + answerText);
        }
        correctResult[currentPosition] = judgeResult;
        btnSubmit.setVisibility(View.GONE);
        return true;
    }

    private void onNext(final MathView textView) {
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!submit()) {
                    return;
                }
                timeCost[currentPosition] = System.currentTimeMillis() - startTime;
                if (currentPosition == 9) {
                    ResultActivity.start(v.getContext(), correctResult, timeCost);
                    return;
                }
                currentPosition++;
                startTime = System.currentTimeMillis();
                btnSubmit.setVisibility(View.VISIBLE);
                IQuestion question = currentPosition < 5 ? generateLinear() : generateQuadratic();
                String questionText = question.getQuestionText();
                textView.setText(questionText + ", what is x?");
                currentQuestion = question;
                generateAnswerLayout(llAnswer, question);
            }
        });
    }

    private void generateAnswerLayout(LinearLayout llAnswer, IQuestion question) {
        llAnswer.removeAllViews();
        int answerCount = question.getAnswerCount();
        for (int i = 0; i < answerCount; i++) {
            LayoutInflater.from(this).inflate(R.layout.layout_answer, llAnswer, true);
        }
        View childAt = llAnswer.getChildAt(0);
        childAt.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 0f, 0f, 0));
        childAt.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 0f, 0f, 0));
    }

    private IQuestion generateLinear() {
        int k = generateParam();
        int d = generateParam();
        return new LinearQuestion(k, d);
    }

    private IQuestion generateQuadratic() {
        int a = generateParam();
        int b = generateParam();
        int c = generateParam();
        QuadraticQuestion quadraticQuestion = new QuadraticQuestion(a, b, c);
        if (!quadraticQuestion.isValid()) {
            return generateQuadratic();
        }
        return quadraticQuestion;
    }

    private int generateParam() {
        return new Random().nextInt(199) - 99;
    }

}
